home *** CD-ROM | disk | FTP | other *** search
/ SGI Freeware 1999 August / SGI Freeware 1999 August.iso / dist / fw_perl.idb / usr / freeware / catman / u_man / cat1 / perlembed.Z / perlembed
Encoding:
Text File  |  1998-10-28  |  49.2 KB  |  1,453 lines

  1.  
  2.  
  3.  
  4.      PPPPEEEERRRRLLLLEEEEMMMMBBBBEEEEDDDD((((1111))))     2222////AAAAuuuugggg////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))      PPPPEEEERRRRLLLLEEEEMMMMBBBBEEEEDDDD((((1111))))
  5.  
  6.  
  7.  
  8.      NNNNAAAAMMMMEEEE
  9.       perlembed - how to embed perl    in your    C program
  10.  
  11.      DDDDEEEESSSSCCCCRRRRIIIIPPPPTTTTIIIIOOOONNNN
  12.       PPPPRRRREEEEAAAAMMMMBBBBLLLLEEEE
  13.  
  14.       Do you want to:
  15.  
  16.       UUUUsssseeee CCCC    ffffrrrroooommmm PPPPeeeerrrrllll????
  17.            Read the    _p_e_r_l_x_s_t_u_t manpage, the _p_e_r_l_x_s manpage, the
  18.            _h_2_x_s manpage, and the _p_e_r_l_g_u_t_s manpage.
  19.  
  20.       UUUUsssseeee aaaa    UUUUnnnniiiixxxx pppprrrrooooggggrrrraaaammmm ffffrrrroooommmm PPPPeeeerrrrllll????
  21.            Read about back-quotes and about    system and exec    in the
  22.            _p_e_r_l_f_u_n_c    manpage.
  23.  
  24.       UUUUsssseeee PPPPeeeerrrrllll ffffrrrroooommmm    PPPPeeeerrrrllll????
  25.            Read about the do entry in the _p_e_r_l_f_u_n_c manpage and the
  26.            eval entry in the _p_e_r_l_f_u_n_c manpage and the require
  27.            entry in    the _p_e_r_l_f_u_n_c manpage and the use entry in the
  28.            _p_e_r_l_f_u_n_c    manpage.
  29.  
  30.       UUUUsssseeee CCCC    ffffrrrroooommmm CCCC????
  31.            Rethink your design.
  32.  
  33.       UUUUsssseeee PPPPeeeerrrrllll ffffrrrroooommmm    CCCC????
  34.            Read on...
  35.  
  36.       RRRROOOOAAAADDDDMMMMAAAAPPPP
  37.  
  38.       the section on _C_o_m_p_i_l_i_n_g _y_o_u_r    _C _p_r_o_g_r_a_m
  39.  
  40.       the section on _A_d_d_i_n_g    _a _P_e_r_l _i_n_t_e_r_p_r_e_t_e_r _t_o _y_o_u_r _C _p_r_o_g_r_a_m
  41.  
  42.       the section on _C_a_l_l_i_n_g _a _P_e_r_l    _s_u_b_r_o_u_t_i_n_e _f_r_o_m    _y_o_u_r _C _p_r_o_g_r_a_m
  43.  
  44.       the section on _E_v_a_l_u_a_t_i_n_g _a _P_e_r_l _s_t_a_t_e_m_e_n_t _f_r_o_m _y_o_u_r _C
  45.       _p_r_o_g_r_a_m
  46.  
  47.       the section on _P_e_r_f_o_r_m_i_n_g _P_e_r_l _p_a_t_t_e_r_n _m_a_t_c_h_e_s _a_n_d
  48.       _s_u_b_s_t_i_t_u_t_i_o_n_s    _f_r_o_m _y_o_u_r _C _p_r_o_g_r_a_m
  49.  
  50.       the section on _F_i_d_d_l_i_n_g _w_i_t_h _t_h_e _P_e_r_l    _s_t_a_c_k _f_r_o_m _y_o_u_r    _C
  51.       _p_r_o_g_r_a_m
  52.  
  53.       the section on _M_a_i_n_t_a_i_n_i_n_g _a _p_e_r_s_i_s_t_e_n_t _i_n_t_e_r_p_r_e_t_e_r
  54.  
  55.       the section on _M_a_i_n_t_a_i_n_i_n_g _m_u_l_t_i_p_l_e _i_n_t_e_r_p_r_e_t_e_r _i_n_s_t_a_n_c_e_s
  56.  
  57.       the section on _U_s_i_n_g _P_e_r_l _m_o_d_u_l_e_s, _w_h_i_c_h _t_h_e_m_s_e_l_v_e_s _u_s_e _C
  58.       _l_i_b_r_a_r_i_e_s, _f_r_o_m _y_o_u_r _C _p_r_o_g_r_a_m
  59.  
  60.  
  61.  
  62.  
  63.      Page 1                        (printed 10/23/98)
  64.  
  65.  
  66.  
  67.  
  68.  
  69.  
  70.      PPPPEEEERRRRLLLLEEEEMMMMBBBBEEEEDDDD((((1111))))     2222////AAAAuuuugggg////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))      PPPPEEEERRRRLLLLEEEEMMMMBBBBEEEEDDDD((((1111))))
  71.  
  72.  
  73.  
  74.       the section on _E_m_b_e_d_d_i_n_g _P_e_r_l    _u_n_d_e_r _W_i_n_3_2
  75.  
  76.       CCCCoooommmmppppiiiilllliiiinnnngggg yyyyoooouuuurrrr CCCC pppprrrrooooggggrrrraaaammmm
  77.  
  78.       If you have trouble compiling    the scripts in this
  79.       documentation, you're    not alone.  The    cardinal rule: COMPILE
  80.       THE PROGRAMS IN EXACTLY THE SAME WAY THAT YOUR PERL WAS
  81.       COMPILED.  (Sorry for    yelling.)
  82.  
  83.       Also,    every C    program    that uses Perl must link in the    _p_e_r_l
  84.       _l_i_b_r_a_r_y.  What's that, you ask?  Perl    is itself written in
  85.       C; the perl library is the collection    of compiled C programs
  86.       that were used to create your    perl executable    (/_u_s_r/_b_i_n/_p_e_r_l
  87.       or equivalent).  (Corollary: you can't use Perl from your C
  88.       program unless Perl has been compiled    on your    machine, or
  89.       installed properly--that's why you shouldn't blithely    copy
  90.       Perl executables from    machine    to machine without also
  91.       copying the _l_i_b directory.)
  92.  
  93.       When you use Perl from C, your C program will--usually--
  94.       allocate, "run", and deallocate a _P_e_r_l_I_n_t_e_r_p_r_e_t_e_r object,
  95.       which    is defined by the perl library.
  96.  
  97.       If your copy of Perl is recent enough    to contain this
  98.       documentation    (version 5.002 or later), then the perl
  99.       library (and _E_X_T_E_R_N._h    and _p_e_r_l._h, which you'll also need)
  100.       will reside in a directory that looks    like this:
  101.  
  102.           /usr/local/lib/perl5/your_architecture_here/CORE
  103.  
  104.       or perhaps just
  105.  
  106.           /usr/local/lib/perl5/CORE
  107.  
  108.       or maybe something like
  109.  
  110.           /usr/opt/perl5/CORE
  111.  
  112.       Execute this statement for a hint about where    to find    CORE:
  113.  
  114.           perl -MConfig -e 'print $Config{archlib}'
  115.  
  116.       Here's how you'd compile the example in the next section,
  117.       the section on _A_d_d_i_n_g    _a _P_e_r_l _i_n_t_e_r_p_r_e_t_e_r _t_o _y_o_u_r _C _p_r_o_g_r_a_m,
  118.       on my    Linux box:
  119.  
  120.           %    gcc -O2    -Dbool=char -DHAS_BOOL -I/usr/local/include
  121.           -I/usr/local/lib/perl5/i586-linux/5.003/CORE
  122.           -L/usr/local/lib/perl5/i586-linux/5.003/CORE
  123.           -o interp    interp.c -lperl    -lm
  124.  
  125.       (That's all one line.)  On my    DEC Alpha running old
  126.  
  127.  
  128.  
  129.      Page 2                        (printed 10/23/98)
  130.  
  131.  
  132.  
  133.  
  134.  
  135.  
  136.      PPPPEEEERRRRLLLLEEEEMMMMBBBBEEEEDDDD((((1111))))     2222////AAAAuuuugggg////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))      PPPPEEEERRRRLLLLEEEEMMMMBBBBEEEEDDDD((((1111))))
  137.  
  138.  
  139.  
  140.       5.003_05, the    incantation is a bit different:
  141.  
  142.           %    cc -O2 -Olimit 2900 -DSTANDARD_C -I/usr/local/include
  143.           -I/usr/local/lib/perl5/alpha-dec_osf/5.00305/CORE
  144.           -L/usr/local/lib/perl5/alpha-dec_osf/5.00305/CORE    -L/usr/local/lib
  145.           -D__LANGUAGE_C__ -D_NO_PROTO -o interp interp.c -lperl -lm
  146.  
  147.       How can you figure out what to add?  Assuming    your Perl is
  148.       post-5.001, execute a    perl -V    command    and pay    special
  149.       attention to the "cc"    and "ccflags" information.
  150.  
  151.       You'll have to choose    the appropriate    compiler (_c_c, _g_c_c, et
  152.       al.) for your    machine: perl -MConfig -e 'print $Config{cc}'
  153.       will tell you    what to    use.
  154.  
  155.       You'll also have to choose the appropriate library directory
  156.       (/_u_s_r/_l_o_c_a_l/_l_i_b/...) for your    machine.  If your compiler
  157.       complains that certain functions are undefined, or that it
  158.       can't    locate -_l_p_e_r_l, then you    need to    change the path
  159.       following the    -L.  If    it complains that it can't find
  160.       _E_X_T_E_R_N._h and _p_e_r_l._h, you need    to change the path following
  161.       the -I.
  162.  
  163.       You may have to add extra libraries as well.    Which ones?
  164.       Perhaps those    printed    by
  165.  
  166.          perl -MConfig -e 'print $Config{libs}'
  167.  
  168.       Provided your    perl binary was    properly configured and
  169.       installed the    EEEExxxxttttUUUUttttiiiillllssss::::::::EEEEmmmmbbbbeeeedddd    module will determine all of
  170.       this information for you:
  171.  
  172.          % cc -o interp interp.c `perl -MExtUtils::Embed -e    ccopts -e ldopts`
  173.  
  174.       If the EEEExxxxttttUUUUttttiiiillllssss::::::::EEEEmmmmbbbbeeeedddd module    isn't part of your Perl
  175.       distribution,    you can    retrieve it from
  176.       http://www.perl.com/perl/CPAN/modules/by-
  177.       module/ExtUtils::Embed.  (If this documentation came from
  178.       your Perl distribution, then you're running 5.004 or better
  179.       and you already have it.)
  180.  
  181.       The EEEExxxxttttUUUUttttiiiillllssss::::::::EEEEmmmmbbbbeeeedddd kit on CPAN also contains    all source
  182.       code for the examples    in this    document, tests, additional
  183.       examples and other information you may find useful.
  184.  
  185.       AAAAddddddddiiiinnnngggg aaaa PPPPeeeerrrrllll    iiiinnnntttteeeerrrrpppprrrreeeetttteeeerrrr ttttoooo yyyyoooouuuurrrr CCCC pppprrrrooooggggrrrraaaammmm
  186.  
  187.       In a sense, perl (the    C program) is a    good example of
  188.       embedding Perl (the language), so I'll demonstrate embedding
  189.       with _m_i_n_i_p_e_r_l_m_a_i_n._c, included    in the source distribution.
  190.       Here's a bastardized,    nonportable version of _m_i_n_i_p_e_r_l_m_a_i_n._c
  191.       containing the essentials of embedding:
  192.  
  193.  
  194.  
  195.      Page 3                        (printed 10/23/98)
  196.  
  197.  
  198.  
  199.  
  200.  
  201.  
  202.      PPPPEEEERRRRLLLLEEEEMMMMBBBBEEEEDDDD((((1111))))     2222////AAAAuuuugggg////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))      PPPPEEEERRRRLLLLEEEEMMMMBBBBEEEEDDDD((((1111))))
  203.  
  204.  
  205.  
  206.           #include <EXTERN.h>        /* from    the Perl distribution      */
  207.           #include <perl.h>            /* from    the Perl distribution      */
  208.  
  209.           static PerlInterpreter *my_perl;    /***    The Perl interpreter    ***/
  210.  
  211.           int main(int argc, char **argv, char **env)
  212.           {
  213.           my_perl = perl_alloc();
  214.           perl_construct(my_perl);
  215.           perl_parse(my_perl, NULL, argc, argv,    (char **)NULL);
  216.           perl_run(my_perl);
  217.           perl_destruct(my_perl);
  218.           perl_free(my_perl);
  219.           }
  220.  
  221.       Notice that we don't use the env pointer.  Normally handed
  222.       to perl_parse    as its final argument, env here    is replaced by
  223.       NULL,    which means that the current environment will be used.
  224.  
  225.       Now compile this program (I'll call it _i_n_t_e_r_p._c) into    an
  226.       executable:
  227.  
  228.           %    cc -o interp interp.c `perl -MExtUtils::Embed -e ccopts    -e ldopts`
  229.  
  230.       After    a successful compilation, you'll be able to use    _i_n_t_e_r_p
  231.       just like perl itself:
  232.  
  233.           %    interp
  234.           print "Pretty Good Perl \n";
  235.           print "10890 - 9801 is ",    10890 -    9801;
  236.           <CTRL-D>
  237.           Pretty Good Perl
  238.           10890 - 9801 is 1089
  239.  
  240.       or
  241.  
  242.           %    interp -e 'printf("%x",    3735928559)'
  243.           deadbeef
  244.  
  245.       You can also read and    execute    Perl statements    from a file
  246.       while    in the midst of    your C program,    by placing the
  247.       filename in _a_r_g_v[_1] before calling _p_e_r_l__r_u_n.
  248.  
  249.       CCCCaaaalllllllliiiinnnngggg aaaa PPPPeeeerrrrllll ssssuuuubbbbrrrroooouuuuttttiiiinnnneeee ffffrrrroooommmm yyyyoooouuuurrrr CCCC    pppprrrrooooggggrrrraaaammmm
  250.  
  251.       To call individual Perl subroutines, you can use any of the
  252.       ppppeeeerrrrllll____ccccaaaallllllll____**** functions    documented in the _p_e_r_l_c_a_l_l manpage.
  253.       In this example we'll    use perl_call_argv.
  254.  
  255.       That's shown below, in a program I'll    call _s_h_o_w_t_i_m_e._c.
  256.  
  257.  
  258.  
  259.  
  260.  
  261.      Page 4                        (printed 10/23/98)
  262.  
  263.  
  264.  
  265.  
  266.  
  267.  
  268.      PPPPEEEERRRRLLLLEEEEMMMMBBBBEEEEDDDD((((1111))))     2222////AAAAuuuugggg////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))      PPPPEEEERRRRLLLLEEEEMMMMBBBBEEEEDDDD((((1111))))
  269.  
  270.  
  271.  
  272.           #include <EXTERN.h>
  273.           #include <perl.h>
  274.  
  275.           static PerlInterpreter *my_perl;
  276.  
  277.           int main(int argc, char **argv, char **env)
  278.           {
  279.           char *args[] = { NULL    };
  280.           my_perl = perl_alloc();
  281.           perl_construct(my_perl);
  282.  
  283.           perl_parse(my_perl, NULL, argc, argv,    NULL);
  284.  
  285.           /*** skipping    perl_run() ***/
  286.  
  287.           perl_call_argv("showtime", G_DISCARD | G_NOARGS, args);
  288.  
  289.           perl_destruct(my_perl);
  290.           perl_free(my_perl);
  291.           }
  292.  
  293.       where    _s_h_o_w_t_i_m_e is a Perl subroutine that takes no arguments
  294.       (that's the _G__N_O_A_R_G_S)    and for    which I'll ignore the return
  295.       value    (that's    the _G__D_I_S_C_A_R_D).     Those flags, and others, are
  296.       discussed in the _p_e_r_l_c_a_l_l manpage.
  297.  
  298.       I'll define the _s_h_o_w_t_i_m_e subroutine in a file    called
  299.       _s_h_o_w_t_i_m_e._p_l:
  300.  
  301.           print "I shan't be printed.";
  302.  
  303.           sub showtime {
  304.           print    time;
  305.           }
  306.  
  307.       Simple enough.  Now compile and run:
  308.  
  309.           %    cc -o showtime showtime.c `perl    -MExtUtils::Embed -e ccopts -e ldopts`
  310.  
  311.           %    showtime showtime.pl
  312.           818284590
  313.  
  314.       yielding the number of seconds that elapsed between January
  315.       1, 1970 (the beginning of the    Unix epoch), and the moment I
  316.       began    writing    this sentence.
  317.  
  318.       In this particular case we don't have    to call    _p_e_r_l__r_u_n, but
  319.       in general it's considered good practice to ensure proper
  320.       initialization of library code, including execution of all
  321.       object DESTROY methods and package END {} blocks.
  322.  
  323.       If you want to pass arguments    to the Perl subroutine,    you
  324.  
  325.  
  326.  
  327.      Page 5                        (printed 10/23/98)
  328.  
  329.  
  330.  
  331.  
  332.  
  333.  
  334.      PPPPEEEERRRRLLLLEEEEMMMMBBBBEEEEDDDD((((1111))))     2222////AAAAuuuugggg////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))      PPPPEEEERRRRLLLLEEEEMMMMBBBBEEEEDDDD((((1111))))
  335.  
  336.  
  337.  
  338.       can add strings to the NULL-terminated args list passed to
  339.       _p_e_r_l__c_a_l_l__a_r_g_v.  For other data types, or to examine return
  340.       values, you'll need to manipulate the    Perl stack.  That's
  341.       demonstrated in the last section of this document: the
  342.       section on _F_i_d_d_l_i_n_g _w_i_t_h _t_h_e _P_e_r_l _s_t_a_c_k _f_r_o_m _y_o_u_r _C _p_r_o_g_r_a_m.
  343.  
  344.       EEEEvvvvaaaalllluuuuaaaattttiiiinnnngggg aaaa PPPPeeeerrrrllll ssssttttaaaatttteeeemmmmeeeennnntttt ffffrrrroooommmm yyyyoooouuuurrrr    CCCC pppprrrrooooggggrrrraaaammmm
  345.  
  346.       Perl provides    two API    functions to evaluate pieces of    Perl
  347.       code.     These are the perl_eval_sv entry in the _p_e_r_l_g_u_t_s
  348.       manpage and the perl_eval_pv entry in    the _p_e_r_l_g_u_t_s manpage.
  349.  
  350.       Arguably, these are the only routines    you'll ever need to
  351.       execute snippets of Perl code    from within your C program.
  352.       Your code can    be as long as you wish;    it can contain
  353.       multiple statements; it can employ the use entry in the
  354.       _p_e_r_l_f_u_n_c manpage, the    require    entry in the _p_e_r_l_f_u_n_c manpage,
  355.       and the do entry in the _p_e_r_l_f_u_n_c manpage to include external
  356.       Perl files.
  357.  
  358.       _p_e_r_l__e_v_a_l__p_v lets us evaluate    individual Perl    strings, and
  359.       then extract variables for coercion into C types.  The
  360.       following program, _s_t_r_i_n_g._c, executes    three Perl strings,
  361.       extracting an    int from the first, a float from the second,
  362.       and a    char * from the    third.
  363.  
  364.  
  365.  
  366.  
  367.  
  368.  
  369.  
  370.  
  371.  
  372.  
  373.  
  374.  
  375.  
  376.  
  377.  
  378.  
  379.  
  380.  
  381.  
  382.  
  383.  
  384.  
  385.  
  386.  
  387.  
  388.  
  389.  
  390.  
  391.  
  392.  
  393.      Page 6                        (printed 10/23/98)
  394.  
  395.  
  396.  
  397.  
  398.  
  399.  
  400.      PPPPEEEERRRRLLLLEEEEMMMMBBBBEEEEDDDD((((1111))))     2222////AAAAuuuugggg////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))      PPPPEEEERRRRLLLLEEEEMMMMBBBBEEEEDDDD((((1111))))
  401.  
  402.  
  403.  
  404.          #include <EXTERN.h>
  405.          #include <perl.h>
  406.  
  407.          static PerlInterpreter *my_perl;
  408.  
  409.          main (int argc, char **argv, char **env)
  410.          {
  411.          char *embedding[] = { "", "-e", "0" };
  412.  
  413.          my_perl = perl_alloc();
  414.          perl_construct( my_perl );
  415.  
  416.          perl_parse(my_perl, NULL, 3, embedding, NULL);
  417.          perl_run(my_perl);
  418.  
  419.          /** Treat $a as an integer **/
  420.          perl_eval_pv("$a = 3; $a **= 2", TRUE);
  421.          printf("a = %d\n", SvIV(perl_get_sv("a", FALSE)));
  422.  
  423.          /** Treat $a as a float **/
  424.          perl_eval_pv("$a = 3.14; $a **= 2", TRUE);
  425.          printf("a = %f\n", SvNV(perl_get_sv("a", FALSE)));
  426.  
  427.          /** Treat $a as a string **/
  428.          perl_eval_pv("$a = 'rekcaH lreP rehtonA tsuJ';    $a = reverse($a);", TRUE);
  429.          printf("a = %s\n", SvPV(perl_get_sv("a", FALSE), PL_na));
  430.  
  431.          perl_destruct(my_perl);
  432.          perl_free(my_perl);
  433.          }
  434.  
  435.       All of those strange functions with _s_v in their names    help
  436.       convert Perl scalars to C types.  They're described in the
  437.       _p_e_r_l_g_u_t_s manpage.
  438.  
  439.       If you compile and run _s_t_r_i_n_g._c, you'll see the results of
  440.       using    _S_v_I_V() to create an int, _S_v_N_V()    to create a float, and
  441.       _S_v_P_V() to create a string:
  442.  
  443.          a = 9
  444.          a = 9.859600
  445.          a = Just Another Perl Hacker
  446.  
  447.       In the example above,    we've created a    global variable    to
  448.       temporarily store the    computed value of our eval'd
  449.       expression.  It is also possible and in most cases a better
  450.       strategy to fetch the    return value from _p_e_r_l__e_v_a_l__p_v()
  451.       instead.  Example:
  452.  
  453.  
  454.  
  455.  
  456.  
  457.  
  458.  
  459.      Page 7                        (printed 10/23/98)
  460.  
  461.  
  462.  
  463.  
  464.  
  465.  
  466.      PPPPEEEERRRRLLLLEEEEMMMMBBBBEEEEDDDD((((1111))))     2222////AAAAuuuugggg////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))      PPPPEEEERRRRLLLLEEEEMMMMBBBBEEEEDDDD((((1111))))
  467.  
  468.  
  469.  
  470.          ...
  471.          SV    *val = perl_eval_pv("reverse 'rekcaH lreP rehtonA tsuJ'", TRUE);
  472.          printf("%s\n", SvPV(val,PL_na));
  473.          ...
  474.  
  475.       This way, we avoid namespace pollution by not    creating
  476.       global variables and we've simplified    our code as well.
  477.  
  478.       PPPPeeeerrrrffffoooorrrrmmmmiiiinnnngggg PPPPeeeerrrrllll ppppaaaatttttttteeeerrrrnnnn mmmmaaaattttcccchhhheeeessss aaaannnndddd ssssuuuubbbbssssttttiiiittttuuuuttttiiiioooonnnnssss ffffrrrroooommmm yyyyoooouuuurrrr
  479.       CCCC pppprrrrooooggggrrrraaaammmm
  480.  
  481.       The _p_e_r_l__e_v_a_l__s_v() function lets us evaluate strings of Perl
  482.       code,    so we can define some functions    that use it to
  483.       "specialize" in matches and substitutions: _m_a_t_c_h(),
  484.       _s_u_b_s_t_i_t_u_t_e(),    and _m_a_t_c_h_e_s().
  485.  
  486.          I32 match(SV *string, char    *pattern);
  487.  
  488.       Given    a string and a pattern (e.g., m/clasp/ or /\b\w*\b/,
  489.       which    in your    C program might    appear as "/\\b\\w*\\b/"),
  490.       _m_a_t_c_h() returns 1 if the string matches the pattern and 0
  491.       otherwise.
  492.  
  493.          int substitute(SV **string, char *pattern);
  494.  
  495.       Given    a pointer to an    SV and an =~ operation (e.g.,
  496.       s/bob/robert/g or tr[A-Z][a-z]), _s_u_b_s_t_i_t_u_t_e()    modifies the
  497.       string within    the AV at according to the operation,
  498.       returning the    number of substitutions    made.
  499.  
  500.          int matches(SV *string, char *pattern, AV **matches);
  501.  
  502.       Given    an SV, a pattern, and a    pointer    to an empty AV,
  503.       _m_a_t_c_h_e_s() evaluates $string =~ $pattern in an    array context,
  504.       and fills in _m_a_t_c_h_e_s with the    array elements,    returning the
  505.       number of matches found.
  506.  
  507.       Here's a sample program, _m_a_t_c_h._c, that uses all three    (long
  508.       lines    have been wrapped here):
  509.  
  510.  
  511.  
  512.  
  513.  
  514.  
  515.  
  516.  
  517.  
  518.  
  519.  
  520.  
  521.  
  522.  
  523.  
  524.  
  525.      Page 8                        (printed 10/23/98)
  526.  
  527.  
  528.  
  529.  
  530.  
  531.  
  532.      PPPPEEEERRRRLLLLEEEEMMMMBBBBEEEEDDDD((((1111))))     2222////AAAAuuuugggg////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))      PPPPEEEERRRRLLLLEEEEMMMMBBBBEEEEDDDD((((1111))))
  533.  
  534.  
  535.  
  536.        #include <EXTERN.h>
  537.        #include <perl.h>
  538.  
  539.        /** my_perl_eval_sv(code, error_check)
  540.        ** kinda like perl_eval_sv(),
  541.        ** but we pop the return value off the stack
  542.        **/
  543.        SV* my_perl_eval_sv(SV *sv, I32 croak_on_error)
  544.        {
  545.            dSP;
  546.            SV* retval;
  547.  
  548.            PUSHMARK(SP);
  549.            perl_eval_sv(sv,    G_SCALAR);
  550.  
  551.            SPAGAIN;
  552.            retval =    POPs;
  553.            PUTBACK;
  554.  
  555.            if (croak_on_error && SvTRUE(ERRSV))
  556.           croak(SvPVx(ERRSV, PL_na));
  557.  
  558.            return retval;
  559.        }
  560.  
  561.        /** match(string, pattern)
  562.        **
  563.        ** Used for matches in a scalar context.
  564.        **
  565.        ** Returns 1    if the match was successful; 0 otherwise.
  566.        **/
  567.  
  568.        I32 match(SV    *string, char *pattern)
  569.        {
  570.            SV *command = NEWSV(1099, 0), *retval;
  571.  
  572.            sv_setpvf(command, "my $string =    '%s'; $string =~ %s",
  573.             SvPV(string,PL_na), pattern);
  574.  
  575.            retval =    my_perl_eval_sv(command, TRUE);
  576.            SvREFCNT_dec(command);
  577.  
  578.            return SvIV(retval);
  579.        }
  580.  
  581.        /** substitute(string, pattern)
  582.        **
  583.        ** Used for =~ operations that modify their left-hand side (s/// and    tr///)
  584.        **
  585.        ** Returns the number of successful matches,    and
  586.        ** modifies the input string    if there were any.
  587.        **/
  588.  
  589.  
  590.  
  591.      Page 9                        (printed 10/23/98)
  592.  
  593.  
  594.  
  595.  
  596.  
  597.  
  598.      PPPPEEEERRRRLLLLEEEEMMMMBBBBEEEEDDDD((((1111))))     2222////AAAAuuuugggg////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))      PPPPEEEERRRRLLLLEEEEMMMMBBBBEEEEDDDD((((1111))))
  599.  
  600.  
  601.  
  602.  
  603.        I32 substitute(SV **string, char *pattern)
  604.        {
  605.            SV *command = NEWSV(1099, 0), *retval;
  606.  
  607.            sv_setpvf(command, "$string = '%s'; ($string =~ %s)",
  608.             SvPV(*string,PL_na), pattern);
  609.  
  610.            retval =    my_perl_eval_sv(command, TRUE);
  611.            SvREFCNT_dec(command);
  612.  
  613.            *string = perl_get_sv("string", FALSE);
  614.            return SvIV(retval);
  615.        }
  616.  
  617.        /** matches(string, pattern,    matches)
  618.        **
  619.        ** Used for matches in an array context.
  620.        **
  621.        ** Returns the number of matches,
  622.        ** and fills    in **matches with the matching substrings
  623.        **/
  624.  
  625.        I32 matches(SV *string, char    *pattern, AV **match_list)
  626.        {
  627.            SV *command = NEWSV(1099, 0);
  628.            I32 num_matches;
  629.  
  630.            sv_setpvf(command, "my $string =    '%s'; @array = ($string    =~ %s)",
  631.             SvPV(string,PL_na), pattern);
  632.  
  633.            my_perl_eval_sv(command,    TRUE);
  634.            SvREFCNT_dec(command);
  635.  
  636.            *match_list = perl_get_av("array", FALSE);
  637.            num_matches = av_len(*match_list) + 1; /** assume $[ is 0 **/
  638.  
  639.            return num_matches;
  640.        }
  641.  
  642.        main    (int argc, char    **argv,    char **env)
  643.        {
  644.            PerlInterpreter *my_perl    = perl_alloc();
  645.            char *embedding[] = { "", "-e", "0" };
  646.            AV *match_list;
  647.            I32 num_matches,    i;
  648.            SV *text    = NEWSV(1099,0);
  649.  
  650.            perl_construct(my_perl);
  651.            perl_parse(my_perl, NULL, 3, embedding, NULL);
  652.  
  653.            sv_setpv(text, "When he is at a convenience store and the bill comes to some amount like    76 cents, Maynard is aware that    there is something he *should* do, something that will enable him to get back a    quarter, but he    has no idea *what*.  He    fumbles    through    his red    squeezey changepurse and gives the boy three extra pennies with    his dollar, hoping that    he might luck into the correct amount.    The boy    gives him back two of his own pennies and then the big shiny quarter that is his prize.    -RICHH");
  654.  
  655.  
  656.  
  657.      Page 10                        (printed 10/23/98)
  658.  
  659.  
  660.  
  661.  
  662.  
  663.  
  664.      PPPPEEEERRRRLLLLEEEEMMMMBBBBEEEEDDDD((((1111))))     2222////AAAAuuuugggg////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))      PPPPEEEERRRRLLLLEEEEMMMMBBBBEEEEDDDD((((1111))))
  665.  
  666.  
  667.  
  668.  
  669.            if (match(text, "m/quarter/")) /** Does text contain 'quarter'? **/
  670.           printf("match: Text contains the word    'quarter'.\n\n");
  671.            else
  672.           printf("match: Text doesn't contain the word 'quarter'.\n\n");
  673.  
  674.            if (match(text, "m/eighth/")) /** Does text contain 'eighth'? **/
  675.           printf("match: Text contains the word    'eighth'.\n\n");
  676.            else
  677.           printf("match: Text doesn't contain the word 'eighth'.\n\n");
  678.  
  679.            /** Match all occurrences of /wi../ **/
  680.            num_matches = matches(text, "m/(wi..)/g", &match_list);
  681.            printf("matches:    m/(wi..)/g found %d matches...\n", num_matches);
  682.  
  683.            for (i =    0; i < num_matches; i++)
  684.           printf("match: %s\n",    SvPV(*av_fetch(match_list, i, FALSE),PL_na));
  685.            printf("\n");
  686.  
  687.            /** Remove all vowels from text **/
  688.            num_matches = substitute(&text, "s/[aeiou]//gi");
  689.            if (num_matches)    {
  690.           printf("substitute: s/[aeiou]//gi...%d substitutions made.\n",
  691.              num_matches);
  692.           printf("Now text is: %s\n\n",    SvPV(text,PL_na));
  693.            }
  694.  
  695.            /** Attempt a substitution **/
  696.            if (!substitute(&text, "s/Perl/C/")) {
  697.           printf("substitute: s/Perl/C...No substitution made.\n\n");
  698.            }
  699.  
  700.            SvREFCNT_dec(text);
  701.            PL_perl_destruct_level =    1;
  702.            perl_destruct(my_perl);
  703.            perl_free(my_perl);
  704.        }
  705.  
  706.       which    produces the output (again, long lines have been
  707.       wrapped here)
  708.  
  709.          match: Text contains the word 'quarter'.
  710.  
  711.          match: Text doesn't contain the word 'eighth'.
  712.  
  713.          matches: m/(wi..)/g found 2 matches...
  714.          match: will
  715.          match: with
  716.  
  717.  
  718.  
  719.  
  720.  
  721.  
  722.  
  723.      Page 11                        (printed 10/23/98)
  724.  
  725.  
  726.  
  727.  
  728.  
  729.  
  730.      PPPPEEEERRRRLLLLEEEEMMMMBBBBEEEEDDDD((((1111))))     2222////AAAAuuuugggg////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))      PPPPEEEERRRRLLLLEEEEMMMMBBBBEEEEDDDD((((1111))))
  731.  
  732.  
  733.  
  734.          substitute: s/[aeiou]//gi...139 substitutions made.
  735.          Now text is: Whn h    s t  cnvnnc str    nd th bll cms t    sm mnt lk 76 cnts,
  736.          Mynrd s wr    tht thr    s smthng h *shld* d, smthng tht    wll nbl    hm t gt    bck
  737.          qrtr, bt h    hs n d *wht*.  H fmbls thrgh hs    rd sqzy    chngprs    nd gvs th by
  738.          thr xtr pnns wth hs dllr, hpng tht    h mght lck nt th crrct mnt.  Th    by gvs
  739.          hm    bck tw f hs wn pnns nd thn th bg shny qrtr tht s hs prz. -RCHH
  740.  
  741.          substitute: s/Perl/C...No substitution made.
  742.  
  743.  
  744.       FFFFiiiiddddddddlllliiiinnnngggg wwwwiiiitttthhhh    tttthhhheeee PPPPeeeerrrrllll ssssttttaaaacccckkkk ffffrrrroooommmm yyyyoooouuuurrrr CCCC pppprrrrooooggggrrrraaaammmm
  745.  
  746.       When trying to explain stacks, most computer science
  747.       textbooks mumble something about spring-loaded columns of
  748.       cafeteria plates: the    last thing you pushed on the stack is
  749.       the first thing you pop off.    That'll    do for our purposes:
  750.       your C program will push some    arguments onto "the Perl
  751.       stack", shut its eyes    while some magic happens, and then pop
  752.       the results--the return value    of your    Perl subroutine--off
  753.       the stack.
  754.  
  755.       First    you'll need to know how    to convert between C types and
  756.       Perl types, with _n_e_w_S_V_i_v() and _s_v__s_e_t_n_v() and    _n_e_w_A_V()    and
  757.       all their friends.  They're described    in the _p_e_r_l_g_u_t_s
  758.       manpage.
  759.  
  760.       Then you'll need to know how to manipulate the Perl stack.
  761.       That's described in the _p_e_r_l_c_a_l_l manpage.
  762.  
  763.       Once you've understood those,    embedding Perl in C is easy.
  764.  
  765.       Because C has    no builtin function for    integer
  766.       exponentiation, let's    make Perl's ** operator    available to
  767.       it (this is less useful than it sounds, because Perl
  768.       implements **    with C's _p_o_w() function).  First I'll create a
  769.       stub exponentiation function in _p_o_w_e_r._p_l:
  770.  
  771.           sub expo {
  772.           my ($a, $b) =    @_;
  773.           return $a ** $b;
  774.           }
  775.  
  776.       Now I'll create a C program, _p_o_w_e_r._c,    with a function
  777.       _P_e_r_l_P_o_w_e_r() that contains all    the perlguts necessary to push
  778.       the two arguments into _e_x_p_o()    and to pop the return value
  779.       out.    Take a deep breath...
  780.  
  781.           #include <EXTERN.h>
  782.           #include <perl.h>
  783.  
  784.           static PerlInterpreter *my_perl;
  785.  
  786.  
  787.  
  788.  
  789.      Page 12                        (printed 10/23/98)
  790.  
  791.  
  792.  
  793.  
  794.  
  795.  
  796.      PPPPEEEERRRRLLLLEEEEMMMMBBBBEEEEDDDD((((1111))))     2222////AAAAuuuugggg////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))      PPPPEEEERRRRLLLLEEEEMMMMBBBBEEEEDDDD((((1111))))
  797.  
  798.  
  799.  
  800.           static void
  801.           PerlPower(int a, int b)
  802.           {
  803.         dSP;                /* initialize stack pointer     */
  804.         ENTER;                /* everything created after here */
  805.         SAVETMPS;            /* ...is a temporary variable.     */
  806.         PUSHMARK(SP);            /* remember the    stack pointer     */
  807.         XPUSHs(sv_2mortal(newSViv(a)));    /* push    the base onto the stack     */
  808.         XPUSHs(sv_2mortal(newSViv(b)));    /* push    the exponent onto stack     */
  809.         PUTBACK;              /* make local stack pointer global */
  810.         perl_call_pv("expo", G_SCALAR);    /* call    the function         */
  811.         SPAGAIN;            /* refresh stack pointer     */
  812.                           /* pop the return    value from stack */
  813.         printf ("%d to the %dth    power is %d.\n", a, b, POPi);
  814.         PUTBACK;
  815.         FREETMPS;            /* free    that return value     */
  816.         LEAVE;                 /*    ...and the XPUSHed "mortal" args.*/
  817.           }
  818.  
  819.           int main (int argc, char **argv, char **env)
  820.           {
  821.         char *my_argv[]    = { "",    "power.pl" };
  822.  
  823.         my_perl    = perl_alloc();
  824.         perl_construct(    my_perl    );
  825.  
  826.         perl_parse(my_perl, NULL, 2, my_argv, (char **)NULL);
  827.         perl_run(my_perl);
  828.  
  829.         PerlPower(3, 4);              /*** Compute 3 **    4 ***/
  830.  
  831.         perl_destruct(my_perl);
  832.         perl_free(my_perl);
  833.           }
  834.  
  835.       Compile and run:
  836.  
  837.           %    cc -o power power.c `perl -MExtUtils::Embed -e ccopts -e ldopts`
  838.  
  839.           %    power
  840.           3    to the 4th power is 81.
  841.  
  842.  
  843.       MMMMaaaaiiiinnnnttttaaaaiiiinnnniiiinnnngggg aaaa    ppppeeeerrrrssssiiiisssstttteeeennnntttt iiiinnnntttteeeerrrrpppprrrreeeetttteeeerrrr
  844.  
  845.       When developing interactive and/or potentially long-running
  846.       applications,    it's a good idea to maintain a persistent
  847.       interpreter rather than allocating and constructing a    new
  848.       interpreter multiple times.  The major reason    is speed:
  849.       since    Perl will only be loaded into memory once.
  850.  
  851.       However, you have to be more cautious    with namespace and
  852.  
  853.  
  854.  
  855.      Page 13                        (printed 10/23/98)
  856.  
  857.  
  858.  
  859.  
  860.  
  861.  
  862.      PPPPEEEERRRRLLLLEEEEMMMMBBBBEEEEDDDD((((1111))))     2222////AAAAuuuugggg////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))      PPPPEEEERRRRLLLLEEEEMMMMBBBBEEEEDDDD((((1111))))
  863.  
  864.  
  865.  
  866.       variable scoping when    using a    persistent interpreter.     In
  867.       previous examples we've been using global variables in the
  868.       default package main.     We knew exactly what code would be
  869.       run, and assumed we could avoid variable collisions and
  870.       outrageous symbol table growth.
  871.  
  872.       Let's    say your application is    a server that will
  873.       occasionally run Perl    code from some arbitrary file.    Your
  874.       server has no    way of knowing what code it's going to run.
  875.       Very dangerous.
  876.  
  877.       If the file is pulled    in by perl_parse(), compiled into a
  878.       newly    constructed interpreter, and subsequently cleaned out
  879.       with perl_destruct() afterwards, you're shielded from    most
  880.       namespace troubles.
  881.  
  882.       One way to avoid namespace collisions    in this    scenario is to
  883.       translate the    filename into a    guaranteed-unique package
  884.       name,    and then compile the code into that package using the
  885.       eval entry in    the _p_e_r_l_f_u_n_c manpage.  In the example below,
  886.       each file will only be compiled once.     Or, the application
  887.       might    choose to clean    out the    symbol table associated    with
  888.       the file after it's no longer    needed.     Using the
  889.       perl_call_argv entry in the _p_e_r_l_c_a_l_l manpage,    We'll call the
  890.       subroutine Embed::Persistent::eval_file which    lives in the
  891.       file persistent.pl and pass the filename and boolean
  892.       cleanup/cache    flag as    arguments.
  893.  
  894.       Note that the    process    will continue to grow for each file
  895.       that it uses.     In addition, there might be AUTOLOADed
  896.       subroutines and other    conditions that    cause Perl's symbol
  897.       table    to grow.  You might want to add    some logic that    keeps
  898.       track    of the process size, or    restarts itself    after a
  899.       certain number of requests, to ensure    that memory
  900.       consumption is minimized.  You'll also want to scope your
  901.       variables with the my    entry in the _p_e_r_l_f_u_n_c manpage whenever
  902.       possible.
  903.  
  904.        package Embed::Persistent;
  905.        #persistent.pl
  906.  
  907.        use strict;
  908.        use vars '%Cache';
  909.        use Symbol qw(delete_package);
  910.  
  911.        sub valid_package_name {
  912.            my($string) = @_;
  913.            $string =~ s/([^A-Za-z0-9\/])/sprintf("_%2x",unpack("C",$1))/eg;
  914.            # second    pass only for words starting with a digit
  915.            $string =~ s|/(\d)|sprintf("/_%2x",unpack("C",$1))|eg;
  916.  
  917.  
  918.  
  919.  
  920.  
  921.      Page 14                        (printed 10/23/98)
  922.  
  923.  
  924.  
  925.  
  926.  
  927.  
  928.      PPPPEEEERRRRLLLLEEEEMMMMBBBBEEEEDDDD((((1111))))     2222////AAAAuuuugggg////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))      PPPPEEEERRRRLLLLEEEEMMMMBBBBEEEEDDDD((((1111))))
  929.  
  930.  
  931.  
  932.            # Dress it up as    a real package name
  933.            $string =~ s|/|::|g;
  934.            return "Embed" .    $string;
  935.        }
  936.  
  937.        sub eval_file {
  938.            my($filename, $delete) =    @_;
  939.            my $package = valid_package_name($filename);
  940.            my $mtime = -M $filename;
  941.            if(defined $Cache{$package}{mtime}
  942.           &&
  943.           $Cache{$package}{mtime} <= $mtime)
  944.            {
  945.           # we have compiled this subroutine already,
  946.           # it has not been updated on disk, nothing left to do
  947.           print    STDERR "already    compiled $package->handler\n";
  948.            }
  949.            else {
  950.           local    *FH;
  951.           open FH, $filename or    die "open '$filename' $!";
  952.           local($/) = undef;
  953.           my $sub = <FH>;
  954.           close    FH;
  955.  
  956.           #wrap    the code into a    subroutine inside our unique package
  957.           my $eval = qq{package    $package; sub handler {    $sub; }};
  958.           {
  959.               #    hide our variables within this block
  960.               my($filename,$mtime,$package,$sub);
  961.               eval $eval;
  962.           }
  963.           die $@ if $@;
  964.  
  965.           #cache it unless we're cleaning out each time
  966.           $Cache{$package}{mtime} = $mtime unless $delete;
  967.            }
  968.  
  969.            eval {$package->handler;};
  970.            die $@ if $@;
  971.  
  972.            delete_package($package)    if $delete;
  973.  
  974.            #take a look if you want
  975.            #print Devel::Symdump->rnew($package)->as_string, $/;
  976.        }
  977.  
  978.        1;
  979.  
  980.        __END__
  981.  
  982.  
  983.  
  984.  
  985.  
  986.  
  987.      Page 15                        (printed 10/23/98)
  988.  
  989.  
  990.  
  991.  
  992.  
  993.  
  994.      PPPPEEEERRRRLLLLEEEEMMMMBBBBEEEEDDDD((((1111))))     2222////AAAAuuuugggg////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))      PPPPEEEERRRRLLLLEEEEMMMMBBBBEEEEDDDD((((1111))))
  995.  
  996.  
  997.  
  998.        /* persistent.c */
  999.        #include <EXTERN.h>
  1000.        #include <perl.h>
  1001.  
  1002.        /* 1    = clean    out filename's symbol table after each request,    0 = don't */
  1003.        #ifndef DO_CLEAN
  1004.        #define DO_CLEAN 0
  1005.        #endif
  1006.  
  1007.        static PerlInterpreter *perl    = NULL;
  1008.  
  1009.        int
  1010.        main(int argc, char **argv, char **env)
  1011.        {
  1012.            char *embedding[] = { "", "persistent.pl" };
  1013.            char *args[] = {    "", DO_CLEAN, NULL };
  1014.            char filename [1024];
  1015.            int exitstatus =    0;
  1016.  
  1017.            if((perl    = perl_alloc())    == NULL) {
  1018.           fprintf(stderr, "no memory!");
  1019.           exit(1);
  1020.            }
  1021.            perl_construct(perl);
  1022.  
  1023.            exitstatus = perl_parse(perl, NULL, 2, embedding, NULL);
  1024.  
  1025.            if(!exitstatus) {
  1026.           exitstatus = perl_run(perl);
  1027.  
  1028.           while(printf("Enter file name: ") && gets(filename)) {
  1029.  
  1030.               /* call the subroutine, passing it the filename as an argument */
  1031.               args[0] =    filename;
  1032.               perl_call_argv("Embed::Persistent::eval_file",
  1033.                      G_DISCARD | G_EVAL, args);
  1034.  
  1035.               /* check $@ */
  1036.               if(SvTRUE(ERRSV))
  1037.               fprintf(stderr, "eval    error: %s\n", SvPV(ERRSV,PL_na));
  1038.           }
  1039.            }
  1040.  
  1041.            PL_perl_destruct_level =    0;
  1042.            perl_destruct(perl);
  1043.            perl_free(perl);
  1044.            exit(exitstatus);
  1045.        }
  1046.  
  1047.       Now compile:
  1048.  
  1049.        % cc    -o persistent persistent.c `perl -MExtUtils::Embed -e ccopts -e    ldopts`
  1050.  
  1051.  
  1052.  
  1053.      Page 16                        (printed 10/23/98)
  1054.  
  1055.  
  1056.  
  1057.  
  1058.  
  1059.  
  1060.      PPPPEEEERRRRLLLLEEEEMMMMBBBBEEEEDDDD((((1111))))     2222////AAAAuuuugggg////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))      PPPPEEEERRRRLLLLEEEEMMMMBBBBEEEEDDDD((((1111))))
  1061.  
  1062.  
  1063.  
  1064.       Here's a example script file:
  1065.  
  1066.        #test.pl
  1067.        my $string =    "hello";
  1068.        foo($string);
  1069.  
  1070.        sub foo {
  1071.            print "foo says:    @_\n";
  1072.        }
  1073.  
  1074.       Now run:
  1075.  
  1076.        % persistent
  1077.        Enter file name: test.pl
  1078.        foo says: hello
  1079.        Enter file name: test.pl
  1080.        already compiled Embed::test_2epl->handler
  1081.        foo says: hello
  1082.        Enter file name: ^C
  1083.  
  1084.  
  1085.       MMMMaaaaiiiinnnnttttaaaaiiiinnnniiiinnnngggg mmmmuuuullllttttiiiipppplllleeee iiiinnnntttteeeerrrrpppprrrreeeetttteeeerrrr iiiinnnnssssttttaaaannnncccceeeessss
  1086.  
  1087.       Some rare applications will need to create more than one
  1088.       interpreter during a session.     Such an application might
  1089.       sporadically decide to release any resources associated with
  1090.       the interpreter.
  1091.  
  1092.       The program must take    care to    ensure that this takes place
  1093.       _b_e_f_o_r_e the next interpreter is constructed.  By default, the
  1094.       global variable PL_perl_destruct_level is set    to 0, since
  1095.       extra    cleaning isn't needed when a program has only one
  1096.       interpreter.
  1097.  
  1098.       Setting PL_perl_destruct_level to 1 makes everything squeaky
  1099.       clean:
  1100.  
  1101.        PL_perl_destruct_level = 1;
  1102.  
  1103.        while(1) {
  1104.            ...
  1105.            /* reset    global variables here with PL_perl_destruct_level = 1 */
  1106.            perl_construct(my_perl);
  1107.            ...
  1108.            /* clean    and reset _everything_ during perl_destruct */
  1109.            perl_destruct(my_perl);
  1110.            perl_free(my_perl);
  1111.            ...
  1112.            /* let's    go do it again!    */
  1113.        }
  1114.  
  1115.       When _p_e_r_l__d_e_s_t_r_u_c_t() is called, the interpreter's syntax
  1116.  
  1117.  
  1118.  
  1119.      Page 17                        (printed 10/23/98)
  1120.  
  1121.  
  1122.  
  1123.  
  1124.  
  1125.  
  1126.      PPPPEEEERRRRLLLLEEEEMMMMBBBBEEEEDDDD((((1111))))     2222////AAAAuuuugggg////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))      PPPPEEEERRRRLLLLEEEEMMMMBBBBEEEEDDDD((((1111))))
  1127.  
  1128.  
  1129.  
  1130.       parse    tree and symbol    tables are cleaned up, and global
  1131.       variables are    reset.
  1132.  
  1133.       Now suppose we have more than    one interpreter    instance
  1134.       running at the same time.  This is feasible, but only    if you
  1135.       used the -DMULTIPLICITY flag when building Perl.  By
  1136.       default, that    sets PL_perl_destruct_level to 1.
  1137.  
  1138.       Let's    give it    a try:
  1139.  
  1140.        #include <EXTERN.h>
  1141.        #include <perl.h>
  1142.  
  1143.        /* we're going to embed two interpreters */
  1144.        /* we're going to embed two interpreters */
  1145.  
  1146.        #define SAY_HELLO "-e", "print qq(Hi, I'm $^X\n)"
  1147.  
  1148.        int main(int    argc, char **argv, char    **env)
  1149.        {
  1150.            PerlInterpreter
  1151.            *one_perl = perl_alloc(),
  1152.            *two_perl = perl_alloc();
  1153.            char *one_args[]    = { "one_perl",    SAY_HELLO };
  1154.            char *two_args[]    = { "two_perl",    SAY_HELLO };
  1155.  
  1156.            perl_construct(one_perl);
  1157.            perl_construct(two_perl);
  1158.  
  1159.            perl_parse(one_perl, NULL, 3, one_args, (char **)NULL);
  1160.            perl_parse(two_perl, NULL, 3, two_args, (char **)NULL);
  1161.  
  1162.            perl_run(one_perl);
  1163.            perl_run(two_perl);
  1164.  
  1165.            perl_destruct(one_perl);
  1166.            perl_destruct(two_perl);
  1167.  
  1168.            perl_free(one_perl);
  1169.            perl_free(two_perl);
  1170.        }
  1171.  
  1172.       Compile as usual:
  1173.  
  1174.        % cc    -o multiplicity    multiplicity.c `perl -MExtUtils::Embed -e ccopts -e ldopts`
  1175.  
  1176.       Run it, Run it:
  1177.  
  1178.        % multiplicity
  1179.        Hi, I'm one_perl
  1180.        Hi, I'm two_perl
  1181.  
  1182.  
  1183.  
  1184.  
  1185.      Page 18                        (printed 10/23/98)
  1186.  
  1187.  
  1188.  
  1189.  
  1190.  
  1191.  
  1192.      PPPPEEEERRRRLLLLEEEEMMMMBBBBEEEEDDDD((((1111))))     2222////AAAAuuuugggg////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))      PPPPEEEERRRRLLLLEEEEMMMMBBBBEEEEDDDD((((1111))))
  1193.  
  1194.  
  1195.  
  1196.       UUUUssssiiiinnnngggg    PPPPeeeerrrrllll mmmmoooodddduuuulllleeeessss,,,, wwwwhhhhiiiicccchhhh tttthhhheeeemmmmsssseeeellllvvvveeeessss uuuusssseeee CCCC lllliiiibbbbrrrraaaarrrriiiieeeessss,,,,    ffffrrrroooommmm
  1197.       yyyyoooouuuurrrr CCCC pppprrrrooooggggrrrraaaammmm
  1198.  
  1199.       If you've played with    the examples above and tried to    embed
  1200.       a script that    _u_s_e()s a Perl module (such as _S_o_c_k_e_t) which
  1201.       itself uses a    C or C++ library, this probably    happened:
  1202.  
  1203.        Can't load module Socket, dynamic loading not available in this perl.
  1204.         (You may need to build a new perl executable which either supports
  1205.         dynamic loading or has the Socket module statically    linked into it.)
  1206.  
  1207.       What's wrong?
  1208.  
  1209.       Your interpreter doesn't know    how to communicate with    these
  1210.       extensions on    its own.  A little glue    will help.  Up until
  1211.       now you've been calling _p_e_r_l__p_a_r_s_e(),    handing    it NULL    for
  1212.       the second argument:
  1213.  
  1214.        perl_parse(my_perl, NULL, argc, my_argv, NULL);
  1215.  
  1216.       That's where the glue    code can be inserted to    create the
  1217.       initial contact between Perl and linked C/C++    routines.
  1218.       Let's    take a look some pieces    of _p_e_r_l_m_a_i_n._c to see how Perl
  1219.       does this:
  1220.  
  1221.        #ifdef __cplusplus
  1222.        #  define EXTERN_C extern "C"
  1223.        #else
  1224.        #  define EXTERN_C extern
  1225.        #endif
  1226.  
  1227.        static void xs_init _((void));
  1228.  
  1229.        EXTERN_C void boot_DynaLoader _((CV*    cv));
  1230.        EXTERN_C void boot_Socket _((CV* cv));
  1231.  
  1232.        EXTERN_C void
  1233.        xs_init()
  1234.        {
  1235.           char *file = __FILE__;
  1236.           /* DynaLoader    is a special case */
  1237.           newXS("DynaLoader::boot_DynaLoader", boot_DynaLoader,    file);
  1238.           newXS("Socket::bootstrap", boot_Socket, file);
  1239.        }
  1240.  
  1241.       Simply put: for each extension linked    with your Perl
  1242.       executable (determined during    its initial configuration on
  1243.       your computer    or when    adding a new extension), a Perl
  1244.       subroutine is    created    to incorporate the extension's
  1245.       routines.  Normally, that subroutine is named
  1246.       _M_o_d_u_l_e::_b_o_o_t_s_t_r_a_p() and is invoked when you say _u_s_e _M_o_d_u_l_e.
  1247.       In turn, this    hooks into an XSUB, _b_o_o_t__M_o_d_u_l_e, which creates
  1248.  
  1249.  
  1250.  
  1251.      Page 19                        (printed 10/23/98)
  1252.  
  1253.  
  1254.  
  1255.  
  1256.  
  1257.  
  1258.      PPPPEEEERRRRLLLLEEEEMMMMBBBBEEEEDDDD((((1111))))     2222////AAAAuuuugggg////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))      PPPPEEEERRRRLLLLEEEEMMMMBBBBEEEEDDDD((((1111))))
  1259.  
  1260.  
  1261.  
  1262.       a Perl counterpart for each of the extension's XSUBs.     Don't
  1263.       worry    about this part; leave that to the _x_s_u_b_p_p and
  1264.       extension authors.  If your extension    is dynamically loaded,
  1265.       DynaLoader creates _M_o_d_u_l_e::_b_o_o_t_s_t_r_a_p() for you on the    fly.
  1266.       In fact, if you have a working DynaLoader then there is
  1267.       rarely any need to link in any other extensions statically.
  1268.  
  1269.       Once you have    this code, slap    it into    the second argument of
  1270.       _p_e_r_l__p_a_r_s_e():
  1271.  
  1272.        perl_parse(my_perl, xs_init,    argc, my_argv, NULL);
  1273.  
  1274.       Then compile:
  1275.  
  1276.        % cc    -o interp interp.c `perl -MExtUtils::Embed -e ccopts -e    ldopts`
  1277.  
  1278.        % interp
  1279.          use Socket;
  1280.          use SomeDynamicallyLoadedModule;
  1281.  
  1282.          print "Now    I can use extensions!\n"'
  1283.  
  1284.       EEEExxxxttttUUUUttttiiiillllssss::::::::EEEEmmmmbbbbeeeedddd can also automate writing the    _x_s__i_n_i_t    glue
  1285.       code.
  1286.  
  1287.        % perl -MExtUtils::Embed -e xsinit -- -o perlxsi.c
  1288.        % cc    -c perlxsi.c `perl -MExtUtils::Embed -e    ccopts`
  1289.        % cc    -c interp.c  `perl -MExtUtils::Embed -e    ccopts`
  1290.        % cc    -o interp perlxsi.o interp.o `perl -MExtUtils::Embed -e    ldopts`
  1291.  
  1292.       Consult the _p_e_r_l_x_s manpage and the _p_e_r_l_g_u_t_s manpage for more
  1293.       details.
  1294.  
  1295.      EEEEmmmmbbbbeeeeddddddddiiiinnnngggg PPPPeeeerrrrllll uuuunnnnddddeeeerrrr WWWWiiiinnnn33332222
  1296.       At the time of this writing (5.004), there are two versions
  1297.       of Perl which    run under Win32.  (The two versions are
  1298.       merging in 5.005.)  Interfacing to ActiveState's Perl
  1299.       library is quite different from the examples in this
  1300.       documentation, as significant    changes    were made to the
  1301.       internal Perl    API.  However, it is possible to embed
  1302.       ActiveState's    Perl runtime.  For details, see    the Perl for
  1303.       Win32    FAQ at
  1304.       http://www.perl.com/perl/faq/win32/Perl_for_Win32_FAQ.html.
  1305.  
  1306.       With the "official" Perl version 5.004 or higher, all    the
  1307.       examples within this documentation will compile and run
  1308.       untouched, although the build    process    is slightly different
  1309.       between Unix and Win32.
  1310.  
  1311.       For starters,    backticks don't    work under the Win32 native
  1312.       command shell.  The ExtUtils::Embed kit on CPAN ships    with a
  1313.       script called    ggggeeeennnnmmmmaaaakkkkeeee, which generates a simple makefile to
  1314.  
  1315.  
  1316.  
  1317.      Page 20                        (printed 10/23/98)
  1318.  
  1319.  
  1320.  
  1321.  
  1322.  
  1323.  
  1324.      PPPPEEEERRRRLLLLEEEEMMMMBBBBEEEEDDDD((((1111))))     2222////AAAAuuuugggg////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))      PPPPEEEERRRRLLLLEEEEMMMMBBBBEEEEDDDD((((1111))))
  1325.  
  1326.  
  1327.  
  1328.       build    a program from a single    C source file.    It can be used
  1329.       like this:
  1330.  
  1331.        C:\ExtUtils-Embed\eg> perl genmake interp.c
  1332.        C:\ExtUtils-Embed\eg> nmake
  1333.        C:\ExtUtils-Embed\eg> interp    -e "print qq{I'm embedded in Win32!\n}"
  1334.  
  1335.       You may wish to use a    more robust environment    such as    the
  1336.       Microsoft Developer Studio.  In this case, run this to
  1337.       generate perlxsi.c:
  1338.  
  1339.        perl    -MExtUtils::Embed -e xsinit
  1340.  
  1341.       Create a new project and Insert -> Files into    Project:
  1342.       perlxsi.c, perl.lib, and your    own source files, e.g.
  1343.       interp.c.  Typically you'll find perl.lib in
  1344.       CCCC::::\\\\ppppeeeerrrrllll\\\\lllliiiibbbb\\\\CCCCOOOORRRREEEE, if not, you    should see the CCCCOOOORRRREEEE directory
  1345.       relative to perl -V:archlib.    The studio will    also need this
  1346.       path so it knows where to find Perl include files.  This
  1347.       path can be added via    the Tools -> Options ->    Directories
  1348.       menu.     Finally, select Build -> Build    interp.exe and you're
  1349.       ready    to go.
  1350.  
  1351.      MMMMOOOORRRRAAAALLLL
  1352.       You can sometimes _w_r_i_t_e _f_a_s_t_e_r _c_o_d_e in C, but    you can    always
  1353.       _w_r_i_t_e    _c_o_d_e _f_a_s_t_e_r in Perl.  Because you can use each from
  1354.       the other, combine them as you wish.
  1355.  
  1356.      AAAAUUUUTTTTHHHHOOOORRRR
  1357.       Jon Orwant <_o_r_w_a_n_t@_t_p_j._c_o_m> and Doug MacEachern
  1358.       <_d_o_u_g_m@_o_s_f._o_r_g>, with    small contributions from Tim Bunce,
  1359.       Tom Christiansen, Guy    Decoux,    Hallvard Furuseth, Dov
  1360.       Grobgeld, and    Ilya Zakharevich.
  1361.  
  1362.       Doug MacEachern has an article on embedding in Volume    1,
  1363.       Issue    4 of The Perl Journal (http://tpj.com).     Doug is also
  1364.       the developer    of the most widely-used    Perl embedding:    the
  1365.       mod_perl system (perl.apache.org), which embeds Perl in the
  1366.       Apache web server.  Oracle, Binary Evolution,    ActiveState,
  1367.       and Ben Sugars's nsapi_perl have used    this model for Oracle,
  1368.       Netscape and Internet    Information Server Perl    plugins.
  1369.  
  1370.       July 22, 1998
  1371.  
  1372.      CCCCOOOOPPPPYYYYRRRRIIIIGGGGHHHHTTTT
  1373.       Copyright (C)    1995, 1996, 1997, 1998 Doug MacEachern and Jon
  1374.       Orwant.  All Rights Reserved.
  1375.  
  1376.       Permission is    granted    to make    and distribute verbatim    copies
  1377.       of this documentation    provided the copyright notice and this
  1378.       permission notice are    preserved on all copies.
  1379.  
  1380.  
  1381.  
  1382.  
  1383.      Page 21                        (printed 10/23/98)
  1384.  
  1385.  
  1386.  
  1387.  
  1388.  
  1389.  
  1390.      PPPPEEEERRRRLLLLEEEEMMMMBBBBEEEEDDDD((((1111))))     2222////AAAAuuuugggg////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))      PPPPEEEERRRRLLLLEEEEMMMMBBBBEEEEDDDD((((1111))))
  1391.  
  1392.  
  1393.  
  1394.       Permission is    granted    to copy    and distribute modified
  1395.       versions of this documentation under the conditions for
  1396.       verbatim copying, provided also that they are    marked clearly
  1397.       as modified versions,    that the authors' names    and title are
  1398.       unchanged (though subtitles and additional authors' names
  1399.       may be added), and that the entire resulting derived work is
  1400.       distributed under the    terms of a permission notice identical
  1401.       to this one.
  1402.  
  1403.       Permission is    granted    to copy    and distribute translations of
  1404.       this documentation into another language, under the above
  1405.       conditions for modified versions.
  1406.  
  1407.  
  1408.  
  1409.  
  1410.  
  1411.  
  1412.  
  1413.  
  1414.  
  1415.  
  1416.  
  1417.  
  1418.  
  1419.  
  1420.  
  1421.  
  1422.  
  1423.  
  1424.  
  1425.  
  1426.  
  1427.  
  1428.  
  1429.  
  1430.  
  1431.  
  1432.  
  1433.  
  1434.  
  1435.  
  1436.  
  1437.  
  1438.  
  1439.  
  1440.  
  1441.  
  1442.  
  1443.  
  1444.  
  1445.  
  1446.  
  1447.  
  1448.  
  1449.      Page 22                        (printed 10/23/98)
  1450.  
  1451.  
  1452.  
  1453.